import React, { PureComponent } from "react"
import moment from "moment"
import { read } from "libs/util/readwirte"

export default class Message extends PureComponent {
  state = {
    page: 0,
    pageSize: 5
  }
  render() {
    const { message = {}, updateMessage, setMessage } = this.props,
      { content = [], totalPages } = message,
      { page, pageSize } = this.state
    return (
      <div
        className="app-message" onMouseLeave={() => {
          let ids = this.getMessageStatus()
          if (ids.length) {
            setMessage(ids)
          }
        }}
      >
        <span
          className="icon icon-tongzhi badeg" alt={this.count()}
        />
        <div
          className="app-message-content">
          <div
            className="prev-btn" onClick={() => {
              if (!totalPages) {
                this.setState({
                  page: page - 1
                })
                updateMessage({
                  pageSize,
                  page: page - 1
                })
              }
            }}
          />
          <ul
            className="content">
            {
              content.map(({ resultType, operationType, operationObject, name, time }, i) => {
                return (
                  <li
                    key={i} className="app-message-content-item">
                    <div>
                      {`${operationType}${name}${operationObject}${resultType}`}
                    </div>
                    <div>
                      {moment(time).format("YYYY-MM-DD HH:mm:ss")}
                    </div>
                  </li>
                )
              })
            }
          </ul>
          <div
            className="next-btn" onClick={() => {
              if (page < totalPages) {
                this.setState({
                  page: page + 1
                })
                let ids = this.getMessageStatus()
                if (ids.length) {
                  setMessage(ids)
                }
                updateMessage({
                  pageSize,
                  page: page + 1
                })
              }
            }}
          />
        </div>
      </div>
    )
  }
  count() {
    return read(this.props, "message.content", []).reduce((x, { isread }) => {
      return isread ? x : x + 1
    }, 0)
  }
  getMessageStatus = () => {
    return read(this.props, "message.content", []).reduce((x, { isread, userId, id }) => {
      return isread ? x : x.concat(id || userId)
    }, [])
  }
  componentDidMount() {
    const { page, pageSize } = this.state
    this.props.updateMessage({ page, pageSize }
    )
  }
}